package com.xqb.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xqb.common.constant.CacheConstants;
import com.xqb.common.core.redis.RedisCache;
import com.xqb.common.utils.DateUtils;
import com.xqb.modules.domain.po.LesCategory;
import com.xqb.modules.mapper.LesCategoryMapper;
import com.xqb.modules.service.ILesCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 课程分类Service业务层处理
 * 
 * @author xqb
 * @date 2024-10-14
 */
@Service
@Slf4j
public class LesCategoryServiceImpl implements ILesCategoryService 
{
    @Autowired
    private LesCategoryMapper lesCategoryMapper;
    @Autowired
    private RedisCache redisCache;
    /**
     * 查询课程分类
     * 
     * @param id 课程分类主键
     * @return 课程分类
     */
    @Override
    public LesCategory selectLesCategoryById(Long id)
    {
        return lesCategoryMapper.selectLesCategoryById(id);
    }

    /**
     * 查询课程分类列表
     * 
     * @param lesCategory 课程分类
     * @return 课程分类
     */
    @Override
    public List<LesCategory> selectLesCategoryList(LesCategory lesCategory) {
        List<LesCategory> lesCategories;

        // 检查缓存中是否存在课程分类列表
        if (redisCache.hasKey(CacheConstants.CATEGORY_KEY)) {
            // 从缓存中获取课程分类列表
            log.info("从缓存中获取课程分类列表");
            lesCategories = redisCache.getCacheList(CacheConstants.CATEGORY_KEY);
        } else {
            // 如果没有缓存，则通过数据库查询课程分类列表
            QueryWrapper<LesCategory> queryWrapper = new QueryWrapper<>();

            queryWrapper.orderByAsc("priority");
            lesCategories = lesCategoryMapper.selectList(queryWrapper);

            // 将查询结果存入缓存
            redisCache.setCacheList(CacheConstants.CATEGORY_KEY, lesCategories);
            log.info("将查询结果存入缓存");
        }

        // 构建课程分类树形结构
        return buildTree(lesCategories, 0L);
    }


    /**
     * 构建树形结构
     *
     * @param categories 所有分类
     * @param parentId   父ID
     * @return 树形结构
     */
    private List<LesCategory> buildTree(List<LesCategory> categories, Long parentId) {
        // 初始化结果列表
        List<LesCategory> result = new ArrayList<>();
        // 遍历所有分类
        for (LesCategory category : categories) {
            // 如果当前分类的父ID等于传入的父ID
            if (category.getParentId().equals(parentId)) {
                // 将当前分类添加到结果列表中
                result.add(category);
                // 递归添加子分类
                // 递归调用buildTree方法，传入所有分类和当前分类的ID作为父ID
                List<LesCategory> children = buildTree(categories, category.getId());
                // 将子分类列表设置到当前分类的子分类属性中
                category.setChildren(children);
            }
        }
        // 返回结果列表
        return result;
    }



    /**
     * 新增课程分类
     * 
     * @param lesCategory 课程分类
     * @return 结果
     */
    @Override
    public int insertLesCategory(LesCategory lesCategory)
    {
        lesCategory.setCreateTime(DateUtils.getNowDate());
        int row = lesCategoryMapper.insertLesCategory(lesCategory);
        redisCache.deleteObject(CacheConstants.CATEGORY_KEY);
        return row;
    }

    /**
     * 修改课程分类
     * 
     * @param lesCategory 课程分类
     * @return 结果
     */
    @Override
    public int updateLesCategory(LesCategory lesCategory)
    {
        lesCategory.setUpdateTime(DateUtils.getNowDate());
        int row=lesCategoryMapper.updateLesCategory(lesCategory);
        redisCache.deleteObject(CacheConstants.CATEGORY_KEY);
        return row;
    }

    /**
     * 修改课程分类状态
     *
     * @param lesCategory 课程分类
     * @return 结果
     */
    @Override
    public int updateLesCategoryStatus(LesCategory lesCategory) {
        // 取出所有需要修改的课程分类
        Map<LesCategory, String> map = new HashMap<>();
        List<Long> childrenIds = new ArrayList<>();
        childrenIds.add(lesCategory.getId());
        // 递归遍历，取出所有子分类
        // 递归遍历所有子分类，将子分类ID存入childrenIds列表中
        getChildrenIds(lesCategory, childrenIds);

        // 构建查询条件
        QueryWrapper<LesCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", childrenIds);

        // 设置需要更新的课程分类状态
        LesCategory category = new LesCategory();
        category.setStatus(lesCategory.getStatus());

        // 执行更新操作
        int row = lesCategoryMapper.update(category, queryWrapper);

        // 删除缓存中的课程分类数据
        redisCache.deleteObject(CacheConstants.CATEGORY_KEY);

        return row;
    }


    private void getChildrenIds(LesCategory lesCategory, List<Long> childrenIds) {
        // 递归遍历所有子分类，将子分类ID存入childrenIds列表中
        List<LesCategory> children = lesCategory.getChildren();
        if (children != null && !children.isEmpty()) {
            for (LesCategory child : children) {
                childrenIds.add(child.getId());
                getChildrenIds(child, childrenIds);
            }
        }
    }

    /**
     * 批量删除课程分类
     * 
     * @param ids 需要删除的课程分类主键
     * @return 结果
     */
    @Override
    public int deleteLesCategoryByIds(Long[] ids)
    {
        int row = lesCategoryMapper.deleteBatchIds(Arrays.asList(ids));
        redisCache.deleteObject(CacheConstants.CATEGORY_KEY);
        return row;
    }

    /**
     * 删除课程分类信息
     * 
     * @param id 课程分类主键
     * @return 结果
     */
    @Override
    public int deleteLesCategoryById(Long id) {
        int row = lesCategoryMapper.deleteById(id);
        redisCache.deleteObject(CacheConstants.CATEGORY_KEY);
        return row;
    }

    @Override
    public List<LesCategory> selectByIds(String[] interestIds) {
        //转List
        List<Long> ids = Arrays.asList(interestIds).stream().map(Long::valueOf).collect(Collectors.toList());
        QueryWrapper<LesCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        return lesCategoryMapper.selectList(queryWrapper);
    }
}
